package br.com.agenda.dao.impl;

import java.util.List;

import org.apache.tapestry5.hibernate.HibernateSessionManager;
import org.apache.tapestry5.services.ApplicationStateManager;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import br.com.agenda.dao.GenericDAO;

public class GenericDAOImpl implements GenericDAO{

	protected HibernateSessionManager hsm;
	protected ApplicationStateManager asm;
	public GenericDAOImpl(HibernateSessionManager hibernateSessionManager, ApplicationStateManager asm)
	{
		this.hsm = hibernateSessionManager;
		this.asm = asm;
	}
	public void saveOrUpdate(Object entity)
	{
		hsm.getSession().saveOrUpdate(entity);
	}
	public void deleteById(long id, Class<?> entityClass)
	{
		hsm.getSession().delete(this.getById(id, entityClass));
	}
	public Object getById(long id, Class<?> entityClass)
	{
		return hsm.getSession().createCriteria(entityClass).add(
				Restrictions.eq("id", id)).uniqueResult();
	}
	//    @SuppressWarnings("unchecked")
	public List<?> getList(Class<?> entityClass)
	{
		return hsm.getSession().createCriteria(entityClass).list();
	}
	public List<?> getListOrderBy(Class<?> entityClass
			, String fieldToOrderBy, int order)
			{
		Criteria c = hsm.getSession().createCriteria(entityClass);
		if (order == ASC_ORDER) {
			c.addOrder(Order.asc(fieldToOrderBy));
		} else {
			c.addOrder(Order.desc(fieldToOrderBy));
		}
		return c.list();
			}
	public List<?> getListByFieldEqualsValue(Class<?> entityClass
			, String fieldName, long fieldValue)
			{
		Criteria c = hsm.getSession().createCriteria(entityClass).add(
				Restrictions.eq(fieldName, fieldValue));
		return c.list();
			}
	public List<?> getListByFieldILikeValue(Class<?> entityClass
			, String fieldName, String fieldValue)
			{
		Criteria c = hsm.getSession().createCriteria(entityClass).add(
				Restrictions.ilike(fieldName, fieldValue, MatchMode.ANYWHERE));
		return c.list();
			}
	public List<?> getListOfTheseFields(Class<?> entityClass, String... fieldsToRead)
	{
		// Para retornar apenas as colunas passadas como parametro.
		Criteria c = hsm.getSession().createCriteria(entityClass);
		for(int i = 0; i < fieldsToRead.length; i++)
		{
			String field = fieldsToRead[i];
			c.setProjection(Projections.property(field));
		}
		return c.list();
	}
} 

